<template>
  <div v-if="isErrorNotificationEnabled" class="error-notification-container">
    <!-- 错误通知图标，红色带数字徽章，根据是否有未读错误来显示 -->
    <el-badge :value="unreadCount" :hidden="!hasUnreadErrors" type="danger">
      <el-button type="danger" :icon="WarningFilled" circle @click="showErrorDrawer" />
    </el-badge>

    <!-- 错误抽屉，显示错误列表和详情 -->
    <el-drawer
      v-model="drawerVisible"
      title="系统错误通知"
      direction="rtl"
      size="50%"
      destroy-on-close
      @closed="onDrawerClosed"
    >
      <div class="error-drawer-content">
        <div class="error-drawer-header">
          <h3>共 {{ errors.length }} 条错误信息</h3>
          <div class="error-drawer-actions">
            <el-button type="primary" size="small" @click="clearAllErrors" :disabled="!errors.length">
              清空所有
            </el-button>
          </div>
        </div>

        <el-empty v-if="!errors.length" description="暂无错误记录" />

        <div v-else class="error-list">
          <el-scrollbar height="calc(100vh - 200px)">
            <el-timeline>
              <el-timeline-item
                v-for="error in errors"
                :key="error.id"
                :type="error.read ? 'primary' : 'danger'"
                :hollow="error.read"
                :timestamp="formatTime(error.timestamp)"
              >
                <el-card
                  shadow="hover"
                  :class="{'unread-error': !error.read}"
                  @click="markAsRead(error.id)"
                >
                  <div class="error-card-header">
                    <span class="error-type">
                      [{{ getSourceLabel(error.source) }}] {{ formatErrorType(error.type) }}
                    </span>
                  </div>
                  <div class="error-message">{{ getSimpleErrorMessage(error.message) }}</div>

                  <!-- 使用collapse将详细信息隐藏在可折叠区域中 -->
                  <el-collapse>
                    <el-collapse-item title="查看详细信息">
                      <div v-if="error.stack" class="error-detail-section">
                        <div class="error-detail-title">错误堆栈:</div>
                        <pre class="error-stack">{{ error.stack }}</pre>
                      </div>

                      <div v-if="error.info" class="error-detail-section">
                        <div class="error-detail-title">附加信息:</div>
                        <pre class="error-info">{{ formatInfo(error.info) }}</pre>
                      </div>

                      <div class="error-detail-section">
                        <div class="error-detail-title">完整错误消息:</div>
                        <pre class="error-full-message">{{ error.message }}</pre>
                      </div>
                    </el-collapse-item>
                  </el-collapse>
                </el-card>
              </el-timeline-item>
            </el-timeline>
          </el-scrollbar>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { WarningFilled } from '@element-plus/icons-vue';
import { useErrorStore, type ErrorRecord } from '../store/modules/error';
import { ElMessageBox, ElNotification } from 'element-plus';

// 使用错误状态管理
const errorStore = useErrorStore();
const drawerVisible = ref(false);

// 从环境变量中获取错误通知是否启用
const isErrorNotificationEnabled = import.meta.env.VITE_ENABLE_ERROR_NOTIFICATION === 'true';

// 初始化错误处理系统
onMounted(async () => {
  if (isErrorNotificationEnabled) {
    await errorStore.initialize();

    // 监听最新错误变化，显示通知
    errorStore.$subscribe((_, state) => {
      const latestError = state.errors[0];
      if (latestError && !latestError.read) {
        // 显示通知
        showErrorNotification(latestError);
      }
    });
  }
});

// 计算属性
const errors = computed(() => errorStore.allErrors);
const hasUnreadErrors = computed(() => errorStore.hasUnreadErrors);
const unreadCount = computed(() => errorStore.unreadCount);

// 显示错误抽屉
function showErrorDrawer() {
  drawerVisible.value = true;
}

// 抽屉关闭后标记所有为已读
function onDrawerClosed() {
  errorStore.markAllAsRead();
}

// 标记单个错误为已读
function markAsRead(errorId: string) {
  errorStore.markAsRead(errorId);
}

// 清空所有错误
async function clearAllErrors() {
  try {
    await ElMessageBox.confirm(
      '确定要清空所有错误记录吗？此操作不可恢复。',
      '警告',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    await errorStore.clearErrors();
  } catch {
    // 用户取消操作
  }
}

// 获取简化的错误消息（只显示前100个字符，不包含堆栈信息）
function getSimpleErrorMessage(message: string): string {
  // 先清除可能包含的堆栈信息
  let simplifiedMessage = message;

  // 移除常见的堆栈信息格式
  if (simplifiedMessage.includes('\n')) {
    simplifiedMessage = simplifiedMessage.split('\n')[0];
  }

  // 如果消息过长，截取前面部分
  const maxLength = 120;
  if (simplifiedMessage.length > maxLength) {
    simplifiedMessage = simplifiedMessage.substring(0, maxLength) + '...';
  }

  return simplifiedMessage;
}

// 格式化错误类型，使其更易读
function formatErrorType(type: string): string {
  // 将camelCase或snake_case转换为空格分隔的单词
  const readable = type
    .replace(/([A-Z])/g, ' $1') // 在大写字母前添加空格
    .replace(/_/g, ' ') // 将下划线替换为空格
    .toLowerCase();

  // 首字母大写
  return readable.charAt(0).toUpperCase() + readable.slice(1);
}

// 格式化时间戳
function formatTime(timestamp: number): string {
  return new Date(timestamp).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
  });
}

// 格式化附加信息
function formatInfo(info: any): string {
  try {
    return typeof info === 'object'
      ? JSON.stringify(info, null, 2)
      : String(info);
  } catch {
    return String(info);
  }
}

// 获取来源标签
function getSourceLabel(source: string): string {
  const sourceMap: Record<string, string> = {
    main: '主进程',
    node: 'Node.js',
    renderer: '渲染进程',
    automation: '自动化任务',
    preload: '预加载脚本'
  };

  return sourceMap[source] || source;
}

// 显示错误通知
function showErrorNotification(error: ErrorRecord) {
  ElNotification({
    title: `系统错误: ${getSourceLabel(error.source)}`,
    message: getSimpleErrorMessage(error.message),
    type: 'error',
    duration: 5000,
    onClick: () => {
      drawerVisible.value = true;
    }
  });
}
</script>

<style scoped>
.error-notification-container {
  position: fixed;
  right: 20px;
  bottom: 20px;
  z-index: 9999;
}

.error-drawer-content {
  padding: 10px;
  height: 100%;
}

.error-drawer-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.error-card-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.error-type {
  font-weight: bold;
  color: #f56c6c;
}

.error-message {
  margin-bottom: 10px;
  white-space: pre-wrap;
  word-break: break-word;
  font-weight: 500;
}

.error-detail-section {
  margin-bottom: 12px;
}

.error-detail-title {
  font-weight: bold;
  margin-bottom: 5px;
  color: #606266;
}

.error-stack, .error-info, .error-full-message {
  font-family: monospace;
  white-space: pre-wrap;
  overflow-x: auto;
  background: #f8f8f8;
  padding: 10px;
  border-radius: 4px;
  color: #333;
  font-size: 12px;
}

.unread-error {
  border-left: 4px solid #f56c6c;
}
</style>
